package com.chungkui.check.expression.impl;

import com.chungkui.check.core.Constants;
import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.expression.BaseExpression;
import com.chungkui.check.handler.insidecheck.InsideType;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: jason
 * @Date: 2020/5/22 14:33
 * @Version 1.0
 */
public class RegExpression extends BaseExpression {
    private String param;
    private String code;
    private Boolean require;
    private Pattern pattern;

    @Override
    public CheckResult match(Map<String, Object> params) {
        String v = MapUtils.getString(params, this.param);
        if (require != null && require && StringUtils.isEmpty(v)) {
            return CheckResult.fail(this.code,this.param,MapUtils.getString(this.msg, Constants.NULL,this.normalMsg),v);
        }
        if (StringUtils.isNotEmpty(v)) {
            Matcher m = pattern.matcher(v);
            boolean isMatch = m.matches();
            if (!isMatch) {
                    return CheckResult.fail(this.code,this.param,MapUtils.getString(this.msg, Constants.FAIL,this.normalMsg),v);
            }
        }
        return CheckResult.success();
    }

    @Override
    public void compile(Map<String, Object> config) {
        this.param = MapUtils.getString(config, "param");
        this.code = MapUtils.getString(config, "code");
        this.require = MapUtils.getBoolean(config, "require",true);
        pattern = Pattern.compile(MapUtils.getString(config, "rule"));
    }


    @Override
    public InsideType getInsideType() {
        return InsideType.NO_INSISE;
    }
}
